package com.example.supermarket;

import android.content.Intent;
import android.os.Bundle;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.supermarket.data.DataBank;
import com.example.supermarket.data.ShopItem;
import com.google.android.material.floatingactionbutton.FloatingActionButton;

import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link ShopItemFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class ShopItemFragment extends Fragment {
    public static final int RESULT_CODE_ADD_DATA = 996;
    private List<ShopItem> shopItems;
    private ShopItemFragment.MyRecyclerViewAdapter recyclerViewAdapter;


    ActivityResultLauncher<Intent> launcherAdd = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
        @Override
        public void onActivityResult(ActivityResult result) {
            Intent data = result.getData();
            int resultCode = result.getResultCode();
            if(resultCode== RESULT_CODE_ADD_DATA){
                if(null==data)return;
                String name=data.getStringExtra("name");
                double price=data.getDoubleExtra("price",0);
                int position=data.getIntExtra("position",shopItems.size());
                shopItems.add(position,new ShopItem(name,R.drawable.a2,price));
                dataBank.saveData();
                recyclerViewAdapter.notifyItemInserted(position);

            }
        }
    });
    ActivityResultLauncher<Intent>  launcherEdit = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
        @Override
        public void onActivityResult(ActivityResult result) {
            Intent data = result.getData();
            int resultCode = result.getResultCode();
            if(resultCode== RESULT_CODE_ADD_DATA) {
                if(null==data)return;
                String name = data.getStringExtra("name");
                double price = data.getDoubleExtra("price", 0);
                int position = data.getIntExtra("position", shopItems.size());
                shopItems.get(position).setName(name);
                shopItems.get(position).setPrice(price);
                dataBank.saveData();
                recyclerViewAdapter.notifyItemChanged(position);
            }
        }
    });
    private DataBank dataBank;



    public ShopItemFragment() {
        // Required empty public constructor
    }

    public static ShopItemFragment newInstance() {
        ShopItemFragment fragment = new ShopItemFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View rootView=inflater.inflate(R.layout.fragment_shop_item, container, false);
        initData();

        FloatingActionButton fabAdd=rootView.findViewById(R.id.floating_action_button_add);
        fabAdd.setOnClickListener(view -> {
            Intent intent=new Intent(this.getContext(),InputActivity.class);
            intent.putExtra("position",shopItems.size());
            launcherAdd.launch(intent);
        });

        RecyclerView mainRecycleView=rootView.findViewById(R.id.recycle_view_items);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this.getContext());
        mainRecycleView.setLayoutManager(layoutManager);

        recyclerViewAdapter = new ShopItemFragment.MyRecyclerViewAdapter(shopItems);
        mainRecycleView.setAdapter(recyclerViewAdapter);
        return rootView;
    }


    public void initData(){
        dataBank = new DataBank(this.getContext());
        shopItems= dataBank.loadData();
    }

    private class MyRecyclerViewAdapter extends RecyclerView.Adapter<ShopItemFragment.MyRecyclerViewAdapter.MyViewHolder> {
        private List<ShopItem> shopItems;

        public MyRecyclerViewAdapter(List<ShopItem> shopItems) {
            this.shopItems=shopItems;
        }

        @NonNull
        @Override
        public ShopItemFragment.MyRecyclerViewAdapter.MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.shop_item_holder, parent, false);

            return new ShopItemFragment.MyRecyclerViewAdapter.MyViewHolder(view);
        }

        @Override
        public void onBindViewHolder(@NonNull ShopItemFragment.MyRecyclerViewAdapter.MyViewHolder holder, int position) {
            holder.getImageView().setImageResource(shopItems.get(position).getPictureId());
            holder.getTextViewName().setText(shopItems.get(position).getName());
            holder.getTextViewPrice().setText(String.valueOf(shopItems.get(position).getPrice()));
        }

        @Override
        public int getItemCount() {
            return shopItems.size();
        }

        private class MyViewHolder extends RecyclerView.ViewHolder implements View.OnCreateContextMenuListener, MenuItem.OnMenuItemClickListener {
            public static final int CONTEXT_MENU_ID_ADD = 1;
            public static final int CONTEXT_MENU_ID_UPDATE = CONTEXT_MENU_ID_ADD+1;
            public static final int CONTEXT_MENU_ID_DELETE = CONTEXT_MENU_ID_ADD+2;

            private final ImageView imageView;
            private final TextView textViewName;
            private final TextView textViewPrice;

            public MyViewHolder(View itemView) {
                super(itemView);

                this.imageView=itemView.findViewById(R.id.image_view_shop_item);
                this.textViewName=itemView.findViewById(R.id.text_view_shop_item_name);
                this.textViewPrice=itemView.findViewById(R.id.text_view_shop_item_price);

                itemView.setOnCreateContextMenuListener(this);

            }

            public ImageView getImageView() {
                return imageView;
            }

            public TextView getTextViewName() {
                return textViewName;
            }

            public TextView getTextViewPrice() {
                return textViewPrice;
            }

            @Override
            public void onCreateContextMenu(ContextMenu contextMenu, View view, ContextMenu.ContextMenuInfo contextMenuInfo) {
                int position=getAdapterPosition();
                MenuItem menuItemAdd=contextMenu.add(Menu.NONE,CONTEXT_MENU_ID_ADD,CONTEXT_MENU_ID_ADD,ShopItemFragment.this.getContext().getResources().getString(R.string.string_menu_add) );
                MenuItem menuItemEdit=contextMenu.add(Menu.NONE,CONTEXT_MENU_ID_UPDATE,CONTEXT_MENU_ID_UPDATE,ShopItemFragment.this.getContext().getResources().getString(R.string.string_menu_edit));
                MenuItem menuItemDelete=contextMenu.add(Menu.NONE,CONTEXT_MENU_ID_DELETE,CONTEXT_MENU_ID_DELETE,ShopItemFragment.this.getContext().getResources().getString(R.string.string_menu_delete));

                menuItemAdd.setOnMenuItemClickListener(this);
                menuItemEdit.setOnMenuItemClickListener(this);
                menuItemDelete.setOnMenuItemClickListener(this);

            }

            @Override
            public boolean onMenuItemClick(MenuItem menuItem) {
                int position= getAdapterPosition();
                Intent intent;
                switch(menuItem.getItemId())
                {

                    case CONTEXT_MENU_ID_ADD:
                        intent=new Intent(ShopItemFragment.this.getContext(),InputActivity.class);
                        intent.putExtra("position",position);
                        launcherAdd.launch(intent);

                        break;
                    case CONTEXT_MENU_ID_UPDATE:
                        intent=new Intent(ShopItemFragment.this.getContext(),InputActivity.class);
                        intent.putExtra("position",position);
                        intent.putExtra("name",shopItems.get(position).getName());
                        intent.putExtra("price",shopItems.get(position).getPrice());
                        launcherEdit.launch(intent);
                        break;

                    case CONTEXT_MENU_ID_DELETE:
                        AlertDialog.Builder alertDB = new AlertDialog.Builder(ShopItemFragment.this.getContext());
                        alertDB.setPositiveButton(ShopItemFragment.this.getContext().getResources().getString(R.string.string_confirmation), (dialogInterface, i) -> {
                            shopItems.remove(position);
                            dataBank.saveData();
                            ShopItemFragment.MyRecyclerViewAdapter.this.notifyItemRemoved(position);
                        });
                        alertDB.setNegativeButton(ShopItemFragment.this.getContext().getResources().getString(R.string.string_cancel), (dialogInterface, i) -> {

                        });
                        alertDB.setMessage(ShopItemFragment.this.getContext().getResources().getString(R.string.string_confirm_delete) +shopItems.get(position).getName()+"？");
                        alertDB.setTitle(ShopItemFragment.this.getContext().getResources().getString(R.string.hint)).show();
                        break;
                }

                return false;
            }
        }
    }

}